package br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.home.info;

import br.edu.ufcg.lsd.wbis.ui.client.beans.UserInfo;
import br.edu.ufcg.lsd.wbis.ui.client.services.UserService;
import br.edu.ufcg.lsd.wbis.ui.client.ui.FormManager;
import br.edu.ufcg.lsd.wbis.ui.client.ui.SubmitFormButtonListener;
import br.edu.ufcg.lsd.wbis.ui.client.ui.loggedin.admin.Updatable;
import br.edu.ufcg.lsd.wbis.ui.client.ui.management.InfoManager;

import com.gwtext.client.core.EventObject;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Window;

/**
 * @author Renato Miceli
 */
public class UpdateInfoButtonListener extends SubmitFormButtonListener<UserInfo> {

	private final InfoManager<UserInfo> infoManager;
	private final InfoManager<UserInfo> loggedInfoManager;
	private final Updatable<UserInfo> parentPortlet;

	public UpdateInfoButtonListener(Window enclosingWindow, FormManager<UserInfo> formManager, Updatable<UserInfo> parentPortlet,
			InfoManager<UserInfo> userInfoManager, InfoManager<UserInfo> loggedInfoManager) {
		super(enclosingWindow, formManager);
		this.infoManager = userInfoManager;
		this.loggedInfoManager = loggedInfoManager;
		this.parentPortlet = parentPortlet;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onClick(Button button, EventObject e) {
		MessageBox.confirm("Confirm", "Are you sure you want to update the personal info?", new MessageBox.ConfirmCallback() {
			public void execute(String btnID) {
				if (btnID.equals("yes")) {
					UserInfo parsedInfo = getParsedInfo();
					UserInfo currentInfo = infoManager.getInfo();
					parsedInfo.setLogin(currentInfo.getLogin());
					parsedInfo.setPassword(currentInfo.getPassword());
					final UserInfo loggedInfo = loggedInfoManager.getInfo();
					UserService.Util.getInstance().updatePersonalInfo(loggedInfo.getLogin(), loggedInfo.getPassword(), parsedInfo,
							new UpdateInfoCallback(parentPortlet));
					getEnclosingWindow().destroy();
				}
			}
		});
	}

}
